package com.ocom.exposeapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.ExposeApiUrl;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.entity.card.EntityCardInfo;
import com.ocom.common.entity.company.EntityComDockApi;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.*;
import com.ocom.common.request.company.GetReplyApiParaRequest;
import com.ocom.common.request.exposeapi.AccountRechargeRequest;
import com.ocom.common.request.exposeapi.AddPersonRequest;
import com.ocom.common.request.exposeapi.CardOperationRequest;
import com.ocom.common.request.exposeapi.ConsumeDetailRequest;
import com.ocom.common.request.exposeapi.ssgl.AllPersonInfoRequest;
import com.ocom.common.request.exposeapi.ssgl.DeptInfoRequest;
import com.ocom.common.request.exposeapi.tecsun.TecsunBaseRequest;
import com.ocom.common.request.payconfig.AddCardInfoVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.utils.ssgl.SSGLReturnDto;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.human.UserInfoVo;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.common.vo.pay.UpdateListRechargeVo;
import com.ocom.common.vo.payconfig.UpdatecardStateVo;
import com.ocom.exposeapi.feign.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2023/3/21
 **/
@Slf4j
@RestController
public class TecsunController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CompanyClientService companyClientService;

	@Autowired
	private HumanFeignService humanFeignService;

	@Autowired
	private PayConfigClientService payConfigClientService;

	@Autowired
	private MqSimple mqSimple;

	@Autowired
	private XfRecordFeign xfRecordFeign;


	//账户充值
	@PostMapping(ExposeApiUrl.URL_ExposeApi_tecsun_AccountRecharge)
	public Result accountRecharge(@Validated @RequestBody AccountRechargeRequest request, BindingResult bindingResult) {

		GetReplyApiParaRequest getReplyApiParaRequest = new GetReplyApiParaRequest();
		getReplyApiParaRequest.setComAppid(request.getComId());
		getReplyApiParaRequest.setDockCode("gkd");
		getReplyApiParaRequest.setDockApiCode("gkd#recharge");
		getReplyApiParaRequest.setKeyType(0);
		Result result = companyClientService.getReplyApiPara(getReplyApiParaRequest);
		if (result.getCode() != 200) {
			return result;
		}

		EntityComDockApi entityComDockApi = JSON.parseObject(JSON.toJSONString(result.getData()), EntityComDockApi.class);


		
		String sign = request.getSign().toLowerCase();
		request.setSign("");
		SortedMap<String, Object> parameters = JSON.parseObject(JSON.toJSONString(request), SortedMap.class);
		String sign1 = SignUtils.createSign(parameters, entityComDockApi.getKey());
		System.out.println(sign1);
		if (!sign.equals(sign1)) {
			return ResultUtil.error(ResultEnum.Err_202);
		}

		UserInfoVo userInfoVo = new UserInfoVo();
		userInfoVo.setComId(entityComDockApi.getComId());
		userInfoVo.setPCode(request.getPCode());
		userInfoVo.setOnlyOne(true);
		Result result1 = humanFeignService.PersonnelGetPersonInfo(userInfoVo);
		if (result1.getCode() != 200) {
			return result1;
		}
		EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result1.getData()), EntityPersonnelInfo.class);

		UpdateListRechargeVo updateListRechargeVo = new UpdateListRechargeVo();
		updateListRechargeVo.setComId(entityComDockApi.getComId());
		updateListRechargeVo.setPId(entityPersonnelInfo.getPId());
		updateListRechargeVo.setRechargeMoney(request.getMoney());
		updateListRechargeVo.setFrom(2);
		updateListRechargeVo.setOrderNo(request.getOrderNo());
		updateListRechargeVo.setDockApiCode(entityComDockApi.getDockApiCode());
		updateListRechargeVo.setDockApiName(entityComDockApi.getApiName());

		if (request.getType() == 1) {
			updateListRechargeVo.setTypeNo(1);
			updateListRechargeVo.setTypeName("现金");
			updateListRechargeVo.setRemark("现金充值:" + request.getMoney() + "分");
		}
		if (request.getType() == 2) {
			updateListRechargeVo.setTypeNo(2);
			updateListRechargeVo.setTypeName("补贴");
			updateListRechargeVo.setRemark("补贴充值:" + request.getMoney() + "分");
		}
		if (request.getType() == 3) {
			updateListRechargeVo.setTypeNo(3);
			updateListRechargeVo.setTypeName("奖金");
			updateListRechargeVo.setRemark("奖金充值:" + request.getMoney() + "分");
		}
		Result result2 = payConfigClientService.UpdateListRecharge(updateListRechargeVo);

		if (result2.getCode() != 200) {
			return result2;
		}
		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result2.getData()));

		jsonObject.put("pCode", entityPersonnelInfo.getPCode());
		jsonObject.put("pName", entityPersonnelInfo.getPName());

		return ResultUtil.success(jsonObject);
	}

	//人员增量操作
	@PostMapping(ExposeApiUrl.URL_ExposeApi_tecsun_PersonOperation)
	public Result personOperation(){
		return ResultUtil.success();
	}

	//人员全量操作
	@PostMapping(ExposeApiUrl.URL_ExposeApi_tecsun_PersonAllOperation)
	public Result personAllOperation(){
		return ResultUtil.success();
	}

	//卡操作
	@PostMapping(ExposeApiUrl.URL_ExposeApi_tecsun_CardOperation)
	public Result cardOperation(@Validated @RequestBody CardOperationRequest request, BindingResult bindingResult) {
		logger.info("进入卡操作接口--------------- 请求参数：" + request.toString());

		ReturnDto returnDto = new ReturnDto();
		checkSign(request, request.getComId(), DockApiCodeEnum.tecsun_deptInfo.getValue(), request.getSign(), returnDto);
		if (null != returnDto.getResultEnum()) {
			return ResultUtil.error(returnDto.getResultEnum());
		}
		Long comId = Long.parseLong(request.getComId());
		UserInfoVo userInfoVo = new UserInfoVo();
		userInfoVo.setComId(comId);
		userInfoVo.setPCode(request.getPCode());
		userInfoVo.setOnlyOne(true);

		logger.info("PersonnelGetPersonInfo--------------- 请求参数：" + userInfoVo.toString());
		Result result1 = humanFeignService.PersonnelGetPersonInfo(userInfoVo);
		if (result1.getCode() != 200) {
			return result1;
		}
		EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result1.getData()), EntityPersonnelInfo.class);

		//1-发卡，2-退卡，3-挂失，4-解挂

		logger.info("getXfUserInfo--------------- 请求参数：" + entityPersonnelInfo.toString());
		Result result3 = humanFeignService.getXfUserInfo(comId, entityPersonnelInfo.getPId());
		if (result3.getCode() != 200) {
			return result3;
		}
		XfUserInfoVo xfUserInfoVo = JSON.parseObject(JSON.toJSONString(result3.getData()), XfUserInfoVo.class);

		if (request.getType() == 1) {
			logger.info("request.getType() == 1,GetCardInfoByPid--------------- 请求参数：" + xfUserInfoVo.toString());
			Result result2 = payConfigClientService.GetCardInfoByPid(comId, entityPersonnelInfo.getPId());
			if (result2.getCode() != 200) {
				return result2;
			}
			//有卡
			if (result2.getData() != null) {
				logger.info("有卡---------------");

				EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(result2.getData()), EntityCardInfo.class);
				if (entityCardInfo.getCardState() == 1) {
					return ResultUtil.error(ResultEnum.Err_815);
				}
				if (entityCardInfo.getCardState() == 0) {
					return ResultUtil.error(ResultEnum.Err_3105);
				}
			}

			AddCardInfoVo addCardInfoVo = new AddCardInfoVo();
			addCardInfoVo.setComId(comId);
			addCardInfoVo.setAccountNo(comId + "P" + entityPersonnelInfo.getPId());
			addCardInfoVo.setCardNo(request.getCardNo());
			addCardInfoVo.setDeposit(0l);
			addCardInfoVo.setEndDate("2032-12-12 23:59:59");
			addCardInfoVo.setCostFee(0l);
			addCardInfoVo.setPId(entityPersonnelInfo.getPId());
			addCardInfoVo.setDeptId(xfUserInfoVo.getDeptId());
			addCardInfoVo.setAccTypeId(xfUserInfoVo.getAccTypeId());
			addCardInfoVo.setUser("JK");
			logger.info("AddCardInfo--------------- 请求参数：" + addCardInfoVo.toString());

			return payConfigClientService.AddCardInfo(addCardInfoVo);
		} else {
			//1-发卡，2-退卡，3-挂失，4-解挂
			UpdatecardStateVo updatecardStateVo = new UpdatecardStateVo();
			updatecardStateVo.setComId(comId);
			updatecardStateVo.setPId(entityPersonnelInfo.getPId());
			updatecardStateVo.setUser("JK");
			updatecardStateVo.setCardNo(request.getCardNo());
			updatecardStateVo.setAccountNo(xfUserInfoVo.getAccountNo());
			if (request.getType() == 2) {
				updatecardStateVo.setCardState(2);
			}
			if (request.getType() == 3) {
				updatecardStateVo.setCardState(0);
			}
			if (request.getType() == 4) {
				updatecardStateVo.setCardState(1);
			}

			logger.info("UpdatecardState--------------- 请求参数：" + updatecardStateVo.toString());

			return payConfigClientService.UpdatecardState(updatecardStateVo);
		}
	}

	//部门操作
	@PostMapping(ExposeApiUrl.URL_ExposeApi_tecsun_DeptOperation)
	public Result deptOperation(){
		return ResultUtil.success();
	}

	//3.5.读取部门信息
	@PostMapping(ExposeApiUrl.URL_ExposeApi_tecsun_DeptInfo)
	public Result deptInfo(@Validated @RequestBody TecsunBaseRequest request) {
		logger.info("进入读取部门信息接口--------------- 请求参数：" + request.toString());

		ReturnDto returnDto = new ReturnDto();
		checkSign(request, request.getComId(), DockApiCodeEnum.tecsun_deptInfo.getValue(), request.getSign(), returnDto);
		if (null != returnDto.getResultEnum()) {
			return ResultUtil.error(returnDto.getResultEnum());
		}

		Result result = humanFeignService.GetDeptInfo(returnDto.getEntityComDockApi().getComId(), null, null);
		if (200 != result.getCode() || null == result.getData()) {
			return ResultUtil.error(ResultEnum.Err_1000);
		}
		return result;
	}

	//3.6.读取在职人员信息
	@PostMapping(ExposeApiUrl.URL_ExposeApi_tecsun_AllPersonInfo)
	public Result allPersonInfo(@Validated @RequestBody AllPersonInfoRequest request) {
		logger.info("进入读取在职人员信息接口--------------- 请求参数：" + request.toString());

		ReturnDto returnDto = new ReturnDto();
		checkSign(request, request.getComAppid(), DockApiCodeEnum.tecsun_allPersonInfo.getValue(), request.getSign(), returnDto);
		if (null != returnDto.getResultEnum()) {
			return ResultUtil.error(returnDto.getResultEnum());
		}
		UserInfoVo userInfoVo = new UserInfoVo();
		userInfoVo.setComId(returnDto.getEntityComDockApi().getComId());
		userInfoVo.setPage(request.getIndex());
		userInfoVo.setSize(request.getSize());
		Result result = humanFeignService.PersonnelGetPersonInfo(userInfoVo);
		if (200 != result.getCode() || null == result.getData()) {
			return ResultUtil.error(ResultEnum.Err_1000);
		}
		return result;
	}

	//设备请求
	@PostMapping(ExposeApiUrl.URL_ExposeApi_tecsun_DeviceRegist)
	public Result deviceRegist(){
		return ResultUtil.success();
	}

	private void checkSign(Object request, String comAppId, String dockApiCode, String requestSign, ReturnDto returnDto) {
		try {
			EntityComDockApi entityComDockApi = getReplyApiPara(comAppId, dockApiCode, 0, returnDto);
			String sign = SignUtils.createSign(request, null, entityComDockApi.getKey());
			if (!requestSign.equals(sign)) {
				returnDto.setResultEnum(ResultEnum.Err_202);
			}
			if (4 > returnDto.getReturnCode()) {
				returnDto.setResultEnum(ResultEnum.Err_201);
			} else if (4 == returnDto.getReturnCode()) {
				returnDto.setResultEnum(ResultEnum.Err_204);
			}
			returnDto.setEntityComDockApi(entityComDockApi);
		} catch (Exception e) {
			returnDto.setResultEnum(ResultEnum.Err_1000);
			e.printStackTrace();
		}

	}

	private EntityComDockApi getReplyApiPara(String appId, String dockApiCode, Integer keyType, ReturnDto returnDto) {
		GetReplyApiParaRequest getReplyApiParaRequest = new GetReplyApiParaRequest();
		getReplyApiParaRequest.setDockCode("tecsun");
		getReplyApiParaRequest.setDockApiCode(dockApiCode);
		getReplyApiParaRequest.setSvrAppid("tecsun");
		getReplyApiParaRequest.setComAppid(appId);
		getReplyApiParaRequest.setKeyType(keyType);

		Result getReplyApiParaResult = companyClientService.getReplyApiPara(getReplyApiParaRequest);
		if (getReplyApiParaResult.getCode() != 200) {
			returnDto.setReturnCode(getReplyApiParaResult.getCode());
			returnDto.setReturnMessage(getReplyApiParaResult.getMsg());
		}
		return JSON.parseObject(JSON.toJSONString(getReplyApiParaResult.getData()), EntityComDockApi.class);
	}

}
